package com.example.mardan.presenter;

import android.content.Context;
import android.util.Log;

import com.example.mardan.contract.CatalogContract;
import com.example.mardan.entity.CatalogEntity;
import com.example.mardan.service.CatalogService;

import java.util.Objects;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class CatalogPresenter implements CatalogContract.BookTypePresenter {
    private CatalogContract.BookTypeView view;
    private Context context ;

    public CatalogPresenter(CatalogContract.BookTypeView view, Context context) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void gatData(String type) {
        String url = "http://apis.juhe.cn/goodbook/" ;
        String key = "02759a01e0ccbeaae0526556634db600" ;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build() ;
        CatalogService service = retrofit.create(CatalogService.class) ;
        service.getData(key , type)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<CatalogEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        view.Loading(true);
                    }

                    @Override
                    public void onNext(@NonNull CatalogEntity catalogEntity) {
                        if (catalogEntity != null){
                            view.showData(catalogEntity);
                        }else {
                            Log.e("空指针警告", "mMainView 为 null" );
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("数据错误", Objects.requireNonNull(e.getMessage()));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
